<?php

/**
 * MVM_MALL 网上商店系统  商品管理
 * ============================================================================
 * 版权所有 (C) 2007-2010 www.mvmmall.com，并保留所有权利。
 * 网站地址: http://www.mvmmall.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * $Author:  www.mvmmall.com  $
 * $Date: 2008-02-27 $
 * $Id: goods.inc.php www.mvmmall.com$
 * ---------------------------------------------
*/

if (!defined('MVMMALL') || !defined('IN_ADMINCP')) {
  exit('Access Denied');
}
//商品管理列表
if($action=='list'){
    require_once MVMMALL_ROOT.'./include/pager.class.php';
    $search_sql = "where uid >0 ";
    //商品排序方式
    !$ps_ac &&  $ps_ac = "DESC";
    switch ($ps_or){
        case 'price': {  $order_sql = " ORDER BY goods_sale_price $ps_ac "; break; }
        case 'stock': {  $order_sql = " ORDER BY goods_stock $ps_ac "; break; }
        case 'date':  {  $order_sql = " ORDER BY register_date $ps_ac "; break; }
        default:      {  $order_sql = " ORDER BY goods_rank ";}
    }
   $ps_ac =  $ps_ac == 'DESC' ? 'ASC' : 'DESC';
   
   //商品分类显示
   if( $ps_cate){
   	require_once MVMMALL_ROOT.'./include/category_tree.class.php';
   	$tree           = new tree();
   	$tree->arr_tree = $cache->get_cache('tree');
   	$arr = implode(',',$tree->get_id($ps_cate));
   	$cat_in = filtering($arr ? $ps_cate.','.$arr: $ps_cate);
   	$search_sql .= "  AND goods_category IN($cat_in)";
   }

    //商品简单搜索
    if ($amode == 'detail_search') {
          $ps_subject &&  $search_sql .= "  AND goods_name LIKE '%".filtering($ps_subject)."%'";
          $ps_code    &&  $search_sql .= "  AND goods_code LIKE '%".filtering($ps_code)."%'";
    } 
    switch ($ps_class)
    {
        case 'sales':       { $search_sql.='  AND goods_class = 1'; break;} 
        case 'check_stock': { $search_sql.='  AND goods_stock <=goods_check_stock'; break;} 
        case 'data':        { $search_sql.=  ' AND goods_stock <=goods_check_stock '; }
        default:
    }
    $total_count = $db->counter("{$tablepre}goods_table","$search_sql");
	$page        = $page ? (int)$page:1;
	$list_num    = 10;
	$rowset      = new Pager($total_count,$list_num,$page);
	$from_record = $rowset->_offset();
    $result      = $db->query("SELECT * FROM `{$tablepre}goods_table` $search_sql $order_sql LIMIT $from_record, $list_num");
    while ($rt   = $db->fetch_array($result)) {
        $rt['url']              = "product.php?action=$rt[uid]";
        $rt['edit']             = "admincp.php?module=$module&action=edit&uid=$rt[uid]";
        $rt['del']              = "admincp.php?module=$module&action=del&uid=$rt[uid]";
        $rt['upv']              = drop_menu(array($lang['no'],$lang['yes']),"upv_$rt[uid]",$rt['upv'],"onchange=\"up_goods('upv','$rt[uid]');\"");
        $rt['goods_name']       = "<input type=\"text\"  name=\"goods_name_$rt[uid]\" id=\"goods_name_$rt[uid]\" onchange=\"up_goods('goods_name','$rt[uid]');\" value=\"$rt[goods_name]\" size=\"22\" maxlength=\"255\" class=\"text\" /> <a href=\"product.php?action=$rt[uid]\" target=\"_blank\"><img src=\"images/admincp/zoom.gif\" align=\"absmiddle\" /></a>";
        $rt['goods_code']       = "<input type=\"text\"  name=\"goods_code_$rt[uid]\" id=\"goods_code_$rt[uid]\" onchange=\"up_goods('goods_code','$rt[uid]');\" value=\"$rt[goods_code]\" size=\"8\" maxlength=\"10\" class=\"text\" />";
        $rt['goods_category']   = cat_menu("goods_category_$rt[uid]",$rt['goods_category'],"onchange=\"up_goods('goods_category','$rt[uid]');\"");
        $rt['goods_status']     = drop_menu($status_arr,"goods_status_$rt[uid]",$rt['goods_status'],"onchange=\"up_goods('goods_status','$rt[uid]');\"");
        $rt['goods_stock']      =  "<input type=\"text\"  name=\"goods_stock_$rt[uid]\" id=\"goods_stock_$rt[uid]\" onchange=\"up_goods('goods_stock','$rt[uid]');\" value=\"$rt[goods_stock]\" size=\"4\" maxlength=\"10\" class=\"text\" />";
        $rt['goods_cost']       =  "<input type=\"text\"  name=\"goods_cost_$rt[uid]\" id=\"goods_cost_$rt[uid]\" onchange=\"up_goods('goods_cost','$rt[uid]');\" value=\"$rt[goods_cost]\" size=\"4\" maxlength=\"10\" class=\"text\" />";
        $rt['goods_sale_price'] = "<input type=\"text\"  name=\"goods_sale_price_$rt[uid]\" id=\"goods_sale_price_$rt[uid]\" onchange=\"up_goods('goods_sale_price','$rt[uid]');\" value=\"$rt[goods_sale_price]\" size=\"4\" maxlength=\"10\" class=\"text\" />";
        $gods_rt[]   = $rt;
    }
    //分类菜单
    $cat_menu    = cat_menu('ps_cate',$ps_cate,'onchange="location.href=\''."admincp.php?module=$module&action=$action&ps_ac=$ps_ac&ps_or=$ps_or&amode=$amode&ps_subject=$ps_subject&ps_code=$ps_code&ps_class=$ps_class&page=$page&ps_cate=".'\' + (this.options[this.selectedIndex].value)"');
    $page_list   = $rowset->link("admincp.php?module=$module&action=$action&ps_ac=$ps_ac&ps_or=$ps_or&ps_cate=$ps_cate&amode=$amode&ps_subject=$ps_subject&ps_code=$ps_code&ps_class=$ps_class&page=");
    require_once template('goods');
    footer();
} 

elseif  ($action=='add' || $action=='edit') {
    if ($setp==1 && $_POST) {
    //判断编码是否重复
    if ($goods_code){
        $goods_code = dhtmlchars($goods_code);
        $code_nums = $db->counter("{$tablepre}goods_table","where goods_code='$goods_code' AND uid <> '$uid'");
        $code_nums>0 &&  exit('对不起，商品编码重复');
    }else {
        if ($action=='add'){
            $list =$db->fetch_row($db->query("SELECT MAX(uid)+1 FROM {$tablepre}goods_table"));
            $goods_id = $list[0];
        }else {
            $goods_id = (int)$uid;
        }
        $goods_code = goods_code($goods_id);
    }
    /**图片处理**/
    require_once 'include/upfile.class.php';
    require_once 'include/watermark.class.php';
    $f = new upfile('gif,jpg,png,jpeg,GIF,JPG,PNG,JPEG');
    $img = new Watermark();
    //上传详细大图
    if($_FILES['goods_file2']['name']!=''){
        file_unlink($goods_file2);
        file_unlink(str_replace("watermark/", "",$goods_file2));//删除大图片水印
        $goods_file2   = $f->upload('goods_file2');
        $goods_big_img = $goods_file2; 
        if($mm_big_wate==1){
            if($mm_wate_class==0){
                $img->wm_image_name = $mm_wate_img;//水印图片
                $img->wm_image_pos = $mm_watermark;
            }else {
                $img->wm_text       = $mm_text_wate;
                $img->wm_text_size  = $mm_text_size;
                $img->wm_text_color = $mm_text_color;
                $img->wm_text_angle = $mm_text_angle;
                $img->wm_text_pos   = $mm_watermark;
                $img->wm_text_font  = "include/fonts/$mm_text_fonts";
            }
            $img->src_image_name = $goods_file2;
            $img->save_file = $f->waterpath.$f->savename;
            $img->create();
            $goods_file2 = $img->save_file;
        }
        
    } 
        //缩图
       if($_FILES['goods_file1']['name']=='' && $_FILES['goods_file2']['name']!='' ){
            file_unlink($goods_file1);
            $goods_file1 = $f->createthumb($goods_big_img,$cf_indexw,$cf_indexh);
            if($mm_thumb_wate==1){
                if($mm_wate_class==0){
                    $img->wm_image_name = $mm_wate_img;//水印图片
                    $img->wm_image_pos = $mm_watermark;
                }else {
                    $img->wm_text = $mm_text_wate;
                    $img->wm_text_size = $mm_text_size;
                    $img->wm_text_color = $mm_text_color;
                    $img->wm_text_angle = $mm_text_angle;
                    $img->wm_text_pos   = $mm_watermark;
                    $img->wm_text_font = "include/fonts/$mm_text_fonts";
                }
                $img->save_file = $goods_file1;
                $img->create($goods_file1);
            }
        }elseif ($_FILES['goods_file1']['name']!='') {
            //原始缩图
            file_unlink($goods_file1);
            $f->savepath = $f->savepath.'/thumb/';
            $goods_file1 = $f->upload('goods_file1');
        }
    /**end**/
    $start_date = time_format($start_date);
    $end_date   = time_format($end_date);
    $up_date    = time_format($up_date);//上架时间
    $goods_mony = intval($goods_mony);//推广币
    $upv        = (int)$upv;
    $use_direct = (int)$use_direct;//是否前台显示
    //是否促销
    $goods_class = $is_event==1 ? 1: 0 ;
    //商品编码
    $row=false;
    $row = array(
                   'member_uid'            => $m_check_uid,
                   'use_direct'            => $use_direct,
                   'goods_class'           => $goods_class,
                   'goods_status'          => $goods_status,
                   'goods_type'            => $typeid,
                   'goods_category'        => $goods_category,
                   'goods_rank'            => $goods_rank,
                   'goods_grant'           => $goods_grant,
                   'goods_skin'            => $goods_skin,
                   'goods_code'            => $goods_code,
                   'goods_name'            => $goods_name,
                   'goods_key'             => $goods_key,
                   'goods_brand'           => $goods_brand,
                   'goods_advance'         => $goods_advance,
                   'goods_add_goods'       => substr(implode(',',array_unique(explode('/',$goods_add_goods))), 0,-1),
                   'goods_check_stock'     => $goods_check_stock,
                   'goods_stock'           => $goods_stock,
                   'goods_cost'            => $goods_cost,
                   'goods_market_price'    => $goods_market_price,
                   'goods_sale_price'      => $goods_sale_price,
                   'event_price'           => $event_price,
                   'price_sale'            => $price_sale,
                   'goods_point'           => $goods_point,
                   'goods_kg'              => $goods_kg,
                   'goods_free_delivery'   => $goods_free_delivery,
                   'goods_file1'           => $goods_file1,
                   'goods_file2'           => $goods_file2,
                   'goods_movie'           => $goods_movie,
                   'goods_addoption1'      => $goods_addoption1,
                   'goods_addoption2'      => $goods_addoption2,
                   'goods_addoption3'      => $goods_addoption3,
                   'goods_addoption4'      => $goods_addoption4,
                   'use_html'              => $use_html,
                   'goods_main'            => $goods_main,
                   'goods_head'            => $goods_head,
                   'goods_foot'            => $goods_foot,
                   'goods_email'           => $goods_email,
                   'goods_supply_id'       => $goods_supply_id,
                   'goods_phone'           => $goods_phone,
                   'start_date'            => $start_date,
                   'end_date'              => $end_date,
                   'register_date'         => $m_now_time,
                   'upv'                   => $upv,
                   'up_date'               => $up_date,
                   'goods_mony'            =>$goods_mony,
                   );         
     if ($action=='add'){
     	$goods_id = $db->insert("{$tablepre}goods_table",$row);
     	//顺序处理
     	$rt_goods = $db->get_one("SELECT goods_rank FROM `{$tablepre}goods_table` WHERE goods_rank = '$goods_rank'");
        $rt_goods['goods_rank']  && $db->query("UPDATE `{$tablepre}goods_table` SET goods_rank = goods_rank + 1 WHERE goods_rank >= '$goods_rank'");
     	unset($row['goods_code'],$row['goods_file1'],$row['goods_file2']);
     	$_SESSION['memory_rt'] = $row;
        //写入商品管理笔记
       $goods_admin_memo && $db->insert("{$tablepre}note",dhtmlchars(array('note_type'=>0,'fid'=>$goods_id,'note_msg'=>$goods_admin_memo)));
     }elseif($action=='edit' && is_numeric($uid)) {
         if($list['goods_rank']) {
             $result = $db->query("UPDATE {$tablepre}goods_table SET goods_rank = goods_rank + 1 WHERE goods_rank >= '$goods_rank' and goods_rank <> '0'");
         }
         $db->update("{$tablepre}goods_table",$row,$where="uid='$uid'");
         $goods_id = $uid;
         //更新商品管理笔记
         $goods_note = $db->get_one("SELECT fid,note_type FROM `{$tablepre}note` WHERE note_type='0' AND fid='$goods_id'");
         $note_array = dhtmlchars(array('note_type'=>0,'fid'=>$goods_id,'note_msg'=>$goods_admin_memo));
         $goods_note==false ? $db->insert("{$tablepre}note",$note_array):$db->update("{$tablepre}note",$note_array,"note_type='0' AND fid='$goods_id'");
     }
    //独立扩展价格
    if ($price_sale==2) {
        $other_price = dhtmlchars($other_price);
        $group_value = dhtmlchars($group_value);
        $db->query(" DELETE FROM {$tablepre}enprice WHERE goods_id='$goods_id'"); //删除扩展价格
        for ($i=0;$i<count($other_price);$i++) {
            $db->query("INSERT INTO {$tablepre}enprice SET goods_id='$goods_id',group_id='$group_value[$i]',price='$other_price[$i]'");
        }
    }
    //商品属性
    if(count($att_value)>0){
    	$att_value = array_unique($att_value);
        $db->query(" DELETE FROM {$tablepre}att_value WHERE goods_id='$goods_id'");
        foreach ($att_value as $key=>$val){
            $bute_id= (int)$att_id[$key];
            if ($val!='' || $att_price[$key]!=''){
            $att_value = dhtmlchars($val);
            $price     = floatval($att_price[$key]);
            $db->query("INSERT INTO `{$tablepre}att_value` SET goods_id='$goods_id',bute_id='$bute_id',att_value='$att_value',att_price='$price'");
            }
        }
    }
    //上传商品像册，并入库
    if($_FILES['gallery']['name'][0]!=''){
        $f = new upfile('gif,jpg,png,bmp','shopimg/gallery/');
        foreach ($_FILES['gallery']['name'] AS $key => $value)
        {
            $upload = array(
            'name' => $_FILES['gallery']['name'][$key],
            'type' => $_FILES['gallery']['type'][$key],
            'tmp_name' => $_FILES['gallery']['tmp_name'][$key],
            'error' => $_FILES['gallery']['error'][$key],
            'size' => $_FILES['gallery']['size'][$key],
            );
            $imgbig = $f->upload($upload);
            $thumb  = $f->createthumb($imgbig,$cf_otherw,$cf_otherh);
            $desc   = dhtmlchars($img_desc[$key]);
            $db->query("INSERT INTO `{$tablepre}gallery`  SET goods_id='$goods_id',imgbig='$imgbig',thumb='$thumb',img_desc='$desc'");
        }
    }
    //end
    //多重分类
    $db->query("DELETE FROM {$tablepre}goods_cat WHERE goods_id='$goods_id'");
    foreach ($other_cat as $val){
    ( is_numeric($val) && $val!=0 ) && $db->query("INSERT INTO `{$tablepre}goods_cat` (goods_id,cat_id) VALUES ('$goods_id','$val')");
    }
    //关联文章
     if ($article_id!=0){
         $action=='edit' && $db->query("DELETE FROM `{$tablepre}goods_article` WHERE goods_id='$goods_id'"); 
         $art = explode(",",$article_id);
         foreach (array_unique($art)  as $val){
             $art_row = array('goods_id'=>intval($goods_id),'article_id'=>intval($val));
             $val!=0 && $db->insert("{$tablepre}goods_article",$art_row);
         }
     }
    //end
    admin_msg('success','admincp.php?module=goods&action=list');
    } else {// 添加商品页面
        $mm_brand  = $cache->get_cache('brand');
        if(is_numeric($uid)){
            $product = $db->get_one("SELECT * FROM `{$tablepre}goods_table` WHERE uid='$uid'");
            $photo = $db->get_all("SELECT * FROM `{$tablepre}gallery` WHERE goods_id='$uid'");//相册数据
            @extract($product,EXTR_OVERWRITE);
            unset($product);
            $arrty_type  = $db->get_one("SELECT a.goods_id,a.bute_id,b.id,b.type_id,c.uid FROM `{$tablepre}att_value` a INNER JOIN `{$tablepre}attribute` b ON a.bute_id=b.id INNER JOIN `{$tablepre}att_type` c ON b.type_id=c.uid WHERE a.goods_id='$uid'");
            $art_list    = $db->get_all("SELECT a.uid,a.board_subject,a.headnum,b.goods_id,b.article_id FROM `{$tablepre}bmain` a LEFT JOIN `{$tablepre}goods_article` b ON a.uid=b.article_id WHERE b.goods_id='$uid' ORDER BY a.headnum ASC");
            $goods_add_goods && $goods_list  = $db->get_all("SELECT uid,goods_name FROM `{$tablepre}goods_table` WHERE uid IN($goods_add_goods) ORDER BY uid DESC");
            $result   = $db->query("SELECT * FROM `{$tablepre}goods_cat` WHERE goods_id='$uid'");
            while ($rt = $db->fetch_array($result)) {
            	$other_cat.=cat_menu('other_cat[]',$rt['cat_id']);
            }
            //商品管理笔记
            $goods_note = $db->get_one("SELECT fid,note_msg,note_type FROM `{$tablepre}note` WHERE note_type='0' AND fid='$uid'");
        }else {
        	$_SESSION['memory_rt'] && @extract($_SESSION['memory_rt'],EXTR_OVERWRITE);
        	$upv               = 1;
            $goods_class       = 0;   
            $goods_rank        = 1;
            $price_sale        = 1;
            $goods_stock       = $mm_nums_stock;
            $goods_check_stock = $mm_check_stock;
            $use_direct        = 1;
            $use_html          = 1;
        }
        $result    = $db->query("SELECT * FROM `{$tablepre}att_type` WHERE enabled =1");
        while ($rt = $db->fetch_array($result)){
            $type_arr[$rt['uid']] = $rt['name'];
        }
        $start_date = $start_date ? date('Y-m-d',$start_date) : date('Y-m-d',$m_now_time);
        $end_date   = $end_date ? date('Y-m-d',$end_date) : date('Y-m-d',$m_now_time);
        $up_date    = $up_date  ? date('Y-m-d',$up_date): date('Y-m-d',$m_now_time);
        drop_check($upv,'upv');
        drop_check($goods_addoption1,'addoption1');
        drop_check($goods_addoption2,'addoption2');
        drop_check($goods_addoption3,'addoption3');
        drop_check($goods_addoption4,'addoption4');
        drop_check($use_direct,'use_direct');
        drop_check($use_html,'use_html');
        drop_check($goods_free_delivery,'free_delivery');
        $type_menu = drop_menu($type_arr,'typeid',$goods_type);
        include_once MVMMALL_ROOT.'./include/fck/fckeditor.php';
        //引入在线编辑器
        $oFCKeditor = new FCKeditor('FCKeditor1');
        $oFCKeditor->BasePath   = 'include/fck/' ;
        $oFCKeditor->ToolbarSet = 'Normal' ;
        $oFCKeditor->Value = $goods_main;
        $oFCKeditor->InstanceName = 'goods_main' ;
        $oFCKeditor->Width = '100%' ;
        $oFCKeditor->Height = '300' ;
        //摸板选择
        $tpl_arr      = tpl_array("./templates/$mm_skin_name",'product');
        $tplpath_menu = drop_menu($tpl_arr,'goods_skin',$goods_skin);
        //查看权限选择
        $grant_menu   = drop_menu($cache->get_cache('grade'),'goods_grant',$goods_grant);
        //展示位置
        unset($status_arr['0']);
        $status_menu = drop_menu($status_arr,'goods_status',$goods_status);
        //分类选择
        $cat_menu     = cat_menu('goods_category',$goods_category);
        $other_menu   = cat_menu('other_cat[]');
        //商品品牌
        $brand_menu   = drop_menu($cache->get_cache('brand'),'goods_brand',$goods_brand);
        $price_chk    = $price_sale == 1 ? 0 :1; //价格选中
        require_once template('goods_add');
        footer();
    }
}
//等级价格
elseif ($action=='goods_price'){
    if ($per==1){
        //返回等级数据
        $arr = $db->get_all("SELECT group_id,group_name,discount,show_price,degree FROM `{$tablepre}grade_table` WHERE show_price='1' ORDER BY degree");
    }else {
        $goods_id = (int)$goods_id;
        $arr      = $db->get_all("SELECT a.*,b.group_name,b.group_id as id FROM `{$tablepre}enprice` a LEFT JOIN `{$tablepre}grade_table` b ON a.group_id=b.group_id  WHERE a.goods_id='$goods_id'");
        $arr == false && $arr = $db->get_all("SELECT group_id,group_name,discount,show_price,degree FROM `{$tablepre}grade_table` WHERE show_price='1' ORDER BY degree");
    }
    require_once MVMMALL_ROOT.'./include/json.class.php';
    $json = new Services_JSON;
    echo $json->encode($arr);
}
//ajax修改
elseif ($action=='up_goods' && is_numeric($uid)){
	unset($row);
    $per       = dhtmlchars($per);
    $val       = $per=='goods_name' ? iconv("gb2312", "UTF-8",dhtmlchars($value)):dhtmlchars($value);
    if ($per=='goods_code') {
    	$code_nums = $db->counter("{$tablepre}goods_table","where goods_code='$val' AND uid <> '$uid'");
    	$code_nums>0 &&  exit('对不起，商品编码重复');
    }
	$row[$per] = $val;
	$row && $db->update("{$tablepre}goods_table",$row,"uid='$uid'");
}
//ajax删除单个相册图片
elseif ($action=='delimg'&&is_numeric($id)){
    $gallery = $db->get_one("SELECT * FROM `{$tablepre}gallery` WHERE imgid='$id'");
    file_unlink($gallery['imgbig']);
    file_unlink($gallery['thumb']);
    $db->query(" DELETE FROM `{$tablepre}gallery`  WHERE imgid='$id'"); 
}
//删除商品
 else if($action=='del'){
 	if (is_numeric($uid)) {
 		unset($goods_rt);
 		$goods_rt = $db->get_one("SELECT uid,goods_file1,goods_file2 FROM `{$tablepre}goods_table` WHERE uid = '$uid'");
 		$goods_rt['goods_file1'] && file_unlink($goods_rt['goods_file1']);
 		$goods_rt['goods_file2'] && file_unlink($goods_rt['goods_file2']);
 		$db->query(" DELETE FROM `{$tablepre}goods_table` WHERE uid='$uid' ");
 		$db->query(" DELETE FROM `{$tablepre}tag` WHERE goods_id='$uid' ");
 	}elseif (is_array($uid_check)){
         unset($goods_rt,$uid);
         for($i=0;$i<count($uid_check);$i++) {
             $uid      = (int)$uid_check[$i];
             $goods_rt = $db->get_one("SELECT uid,goods_file1,goods_file2 FROM `{$tablepre}goods_table` WHERE uid = '$uid'");
             $goods_rt['goods_file1'] && file_unlink($goods_rt['goods_file1']);
             $goods_rt['goods_file2'] && file_unlink($goods_rt['goods_file2']);
             $db->query(" DELETE FROM `{$tablepre}goods_table` WHERE uid='$uid' ");
             $db->query(" DELETE FROM `{$tablepre}tag` WHERE goods_id='$uid' ");
         }
             admin_msg('success',dreferer());
     }else {
         admin_msg('pass_worng');
     }
}